<script setup lang="ts">
import { ref, defineAsyncComponent, onMounted, nextTick, onUnmounted } from "vue";
import { eventBus } from "@/views/all/visual/template/utils";

const emits = defineEmits(["generalEvent"]);
const imgArr: Record<string, any>[] = [];
const activeName = ref("layerBase");
let compArr = ["layerConduitup", "layerBase", "layerConduitdown", "layerWire", "layerHse"];

for (let i = 0; i < compArr.length; i++) {
  let comp = defineAsyncComponent(() => import(`../../assets/filter/${compArr[i]}.svg?component`));
  let val = {
    comp,
    name: compArr[i]
  };
  imgArr.push(val);
}
function camelCaseToSeparated(str, separator = "_") {
  return (
    str
      // Insert the separator before all upper case letters.
      .replace(/([a-z])([A-Z])/g, `$1${separator}$2`)
      // Convert the string to lower case.
      .toLowerCase()
  );
}
const generalEvent = item => {
  activeName.value = item.name;
  emits("generalEvent", { type: "compFilter", compEmitData: camelCaseToSeparated(item.name) });
};
onMounted(() => {
  nextTick(() => {
    setTimeout(() => {
      //打一个补丁，因为图片加载速度慢，导致事件限于图片执行，打一个临时补丁
      emits("generalEvent", { type: "compFilter", compEmitData: camelCaseToSeparated(activeName.value) });
    }, 1000);
    // emits("generalEvent", { type: "compFilter", compEmitData: camelCaseToSeparated(activeName.value) });
  });
  eventBus.on("layerAction", name => {
    generalEvent({ name });
  });
});
onUnmounted(() => {
  eventBus.off("layerAction");
});
</script>

<template>
  <div class="max[500px] h-[40px] flex flex-wrap justify-start items-center bottom-[80px]">
    <div
      v-for="item in imgArr"
      :key="item.name"
      class="w-[40px] h-[40px] cursor-pointer grow-0 shrink-0 bg-white flex justify-center items-center mr-1"
      @click="generalEvent(item)"
    >
      <component
        :is="item.comp"
        class="w-[24px] h-[24px] hover:text-[#3B82F6] active:text-[#3B82F6]"
        :class="{ 'text-[#3B82F6]': activeName === item.name, 'text-gray-500': activeName !== item.name }"
      />
    </div>
  </div>
</template>
